package com.cqie.wanling.controller;

import com.burial.common.log.MyLog;
import com.cqgc.entity.User;
import com.cqgc.service.UserService;
import com.cqie.wanling.domain.DataReturn;
import com.cqie.wanling.domain.RegisterUser;
import com.cqie.wanling.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/04/19/10:23
 **/
@Controller
@ResponseBody
@Api(tags = "用户注册接口")
public class RegisterController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    @MyLog(type = "用户注册", msg = "用户注册操作")  //这里使用的自定义注解
    public DataReturn register(@RequestBody RegisterUser registerUser) {
        if(registerUser.getCode().equals("")){
            DataReturn dataReturn = new DataReturn();
            dataReturn.setCode("401");
            dataReturn.setMesg("验证码为空");
            return dataReturn;
        }
        //由于获取验证码的流程已经验证过账号合法性，这里不在做拦截检查，仅核验验证码
        else if (RedisUtil.get(registerUser.getAccount()).equals(registerUser.getCode())) {
            //拿到数据做前置处理
            if (registerUser.getRole() == 1 || registerUser.getRole() == 2 || registerUser.getRole() == 3) {
                DataReturn dataReturn = new DataReturn();
                User user = new User();
                user.setAccount(registerUser.getAccount());
                user.setAddress(registerUser.getAddress());
                user.setPassword(registerUser.getPassword());
                user.setPhone(registerUser.getPhone());
                user.setRole(registerUser.getRole());
                user.setState(1);
                user.setUsername(registerUser.getUsername());
                int result = userService.addUser(user);
                if (result > 0) {
                    dataReturn.setCode("200");
                    dataReturn.setMesg("注册成功!");
                    RedisUtil.del(registerUser.getAccount());
                } else {
                    dataReturn.setCode("409");
                    dataReturn.setMesg("注册失败!");
                }
                return dataReturn;
            } else {
                DataReturn dataReturn = new DataReturn();
                dataReturn.setCode("408");
                dataReturn.setMesg("注册失败，角色信息不合法!");
                return dataReturn;
            }
//        return Result.error("注册失败");
        }
        DataReturn dataReturn = new DataReturn();
        dataReturn.setCode("405");
        dataReturn.setMesg("验证码不正确");
        return dataReturn;
    }
}
